package RequestHandle;

import entity.RpcRequest;
import entity.RpcResponse;
import registerCenter.ServiceRegistry;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class RequestHandlerThread implements Runnable{
    private Socket clientSocket;
    private ServiceRegistry serviceRegistry;
    private RequestHandler requestHandler;

    public RequestHandlerThread(Socket clientSocket, ServiceRegistry serviceRegistry, RequestHandler requestHandler){
        this.clientSocket = clientSocket;
        this.serviceRegistry = serviceRegistry;
        this.requestHandler = requestHandler;
    }

    @Override
    public void run() {
        try(ObjectInputStream inputStream = new ObjectInputStream(clientSocket.getInputStream());
            ObjectOutputStream outputStream = new ObjectOutputStream(clientSocket.getOutputStream())){
            RpcRequest request = (RpcRequest) inputStream.readObject();
            String interfaceName = request.getInterfaceName();

            Object service = serviceRegistry.getService(interfaceName);

            Object result = requestHandler.handle(service, request);
            outputStream.writeObject(RpcResponse.success(result));
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
